//
//  UIFont+utils.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "UIFont+utils.h"

@implementation UIFont (utils)

@end

UIFont* UIFontFromString(NSString* fontname){
    NSString *preset=@"Helvetica";
    CGFloat minfont=8;

    NSString *font=nil;
    CGFloat fontsize=0;
	if (fontname==nil) {
        font=preset;
        fontsize=16;
	}else{
        NSArray *args=[fontname componentsSeparatedByString:@"@"];
        if (args.count==2) {
            font=[args objectAtIndex:0];
            if (!fontInstalled(font)) {
                font=preset;
            }
            NSString *size=[args objectAtIndex:1];
            fontsize=MAX(minfont, size.intValue);
        }else{
            font=preset;
            fontsize=MAX(minfont, fontname.intValue);
        }
    }
    return [UIFont fontWithName:font size:fontsize];
}

BOOL fontInstalled(NSString* fontname){
    BOOL installed=NO;
	NSArray *familys=[UIFont familyNames];
	for (NSString *familyName in familys) {
		NSArray *fonts=[UIFont fontNamesForFamilyName:familyName];
        for (NSString *font in fonts) {
            if ([font isEqualToString:fontname]) {
                installed=YES;
            }
        }
	}
    return installed;
}

void availableFonts(){
    NSMutableDictionary *list=[NSMutableDictionary dictionary];
	NSArray *familys=[UIFont familyNames];
	for (NSString *familyName in familys) {
		NSArray *fonts=[UIFont fontNamesForFamilyName:familyName];
        [list setValue:fonts forKey:familyName];
	}
    NSLog(@"available fonts: %@",list);
};

